<?php
namespace gnomephp;

/**
 * 
 * Lightweight spl autoloader for gnomephp namespace and sub namespace.
 * Takes use of GNOME_FW_PATH ( Location is to the root namespace "gnomephp".
 * @author peec
 *
 */
class AutoLoader {
        public function __construct() {
            spl_autoload_register(array($this, 'loader'));
        }
        
        
        private function loader($className) {
        	
        	// Strip of \ start of ns if any.
        	if (substr($className, 0, 1) == '\\')$className = substr($className, 1);
        	
        	if (substr($className, 0, 8) == 'gnomephp'){
        		$clsName = $this->dirify(substr($className, 9, strlen($className)));
        		
        		$f = GNOME_FW_PATH.DIRECTORY_SEPARATOR.$clsName.'.php';
            	if (file_exists($f))require_once $f;
            	else throw new AutoLoaderException("Could not include file $f because it did not exist.");
        	}
        	
        	if (@defined('GNOME_APP_NS') && @defined('GNOME_APP_PATH') && substr($className, 0, strlen(GNOME_APP_NS)) == GNOME_APP_NS){
        		$clsName = $this->dirify(substr($className, strlen(GNOME_APP_NS)+1, strlen($className)));
        		$f = GNOME_APP_PATH . DIRECTORY_SEPARATOR.$clsName.'.php';
        		if (file_exists($f))require_once $f;
            	else throw new AutoLoaderException("Could not include file $f because it did not exist.");
        	}
        }
        
        /**
         * Converts ns path ( eg. gnomephp\sub\Test )
         * to
         * gnomephp (DIRECTORY_SEPARATOR) sub (DIRECTORY_SEPARATOR) Test
         * 
         * This must be done since linux systems uses another directory separator then windows systems.
         * @param string $ns A namespace with associated class. eg. gnomephp\sub\Test
         */
        private function dirify($ns){
        	return str_replace('\\', DIRECTORY_SEPARATOR, $ns);
        }
        
        
 }